package com.kangye.exam.filter;

import com.kangye.exam.utils.RedisTool;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Component
@WebFilter(filterName = "user_load_filter",urlPatterns = "/*")
public class UserLoginFilter implements Filter {
    @Resource
    private RedisTool redisTool;
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }
    /*
    * 解决跨域请求
    * 校验用户是否登录
    * */
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest req = (HttpServletRequest) servletRequest;
        HttpServletResponse resp=(HttpServletResponse) servletResponse;
        //*表示允许所有域名跨域
        resp.setContentType("text/html;charset=utf-8");
        resp.addHeader("Access-Control-Allow-Origin", "*");
        resp.addHeader("Access-Control-Allow-Headers",
                "Origin, X-Requested-With, Content-Type, Accept");
        //允许跨域的Http方法
        resp.addHeader("Access-Control-Allow-Methods", "GET,POST,PUT,DELETE");
        resp.addHeader("Access-Control-Max-Age", "0");
        resp.addHeader("Access-Control-Allow-Credentials","true");
        resp.addHeader("XDomainRequestAllowed","1");
//        User user=new User();
//        user.setUsername(req.getParameter("username"));
//        user.setPassword(req.getParameter("pas"));
        int flag=0;
//        List<Object> ulist=redisTool.lGet("user",0,-1);
//        if (ulist.size()>0 && req.getRequestURI().contains("redis_test")){
//            for (Object u:ulist) {
//                if (JsonUtil.bean2Json(user).equals(u)){
//                    flag=1;
//                    resp.sendRedirect("rpt");
//                    break;
//                }
//            }
//        }
        if (flag==0){
            filterChain.doFilter(servletRequest, servletResponse);
        }
    }

    @Override
    public void destroy() {

    }
}
